package cn.math.appmath.dao.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.math.appmath.dao.UserDao;
import cn.math.appmath.entity.User;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
	private static final Log log = LogFactory.getLog(UserDaoImpl.class);
	
	public User findUser() {
		log.debug("find User instance");
		try {
			Query querty = getSession().createQuery("from User order by uno");
			querty.setMaxResults(1);
			User user = (User)querty.uniqueResult();
			log.debug("find successful");
			return user;
		} catch (RuntimeException re) {
			log.error("find failed", re);
			re.printStackTrace();
			return null;
		}
	}
	
	public int updateUser(User user){
		try{
			String hql = "update User set uname=?,upassword=? where uno=?";
			Query query = getSession().createQuery(hql);
			query.setParameter(0, user.getUname());
			query.setParameter(1, user.getUpassword());
			query.setParameter(2, user.getUno());
			int num = query.executeUpdate();
			return num;
		}catch(Exception ex){
			ex.printStackTrace();
			return 0;
		}
	}
	
	public List<User> findByExample(User user){
		log.debug("find User by name and password");
		try {
			String hql = "from User where uname=? and upassword=?";
			Query queryObject = getSession().createQuery(hql);
			queryObject.setParameter(0, user.getUname());
			queryObject.setParameter(1, user.getUpassword());
			return (List<User>)queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by name and pasword failed", re);
			re.printStackTrace();
			return null;
		}
	}
	
}
